/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the piggy.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.piggy.common.satoken.feign;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.satoken.constants.SaTokenConst;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;

/**
 * @author shark
 * @date 2018/8/13 扩展OAuth2FeignRequestInterceptor
 */
@Slf4j
public class SaTokenFeignClientInterceptor implements RequestInterceptor {

	/**
	 * Create a template with the header of provided name and extracted extract 1. 如果使用
	 * 非web 请求，header 区别 2. 根据authentication 还原请求token
	 * @param template
	 */
	@Override
	public void apply(RequestTemplate template) {
		Collection<String> fromHeader = template.headers().get(SecurityConstants.FROM_SOURCE);
		if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstants.INNER)) {
			return;
		}
		String token = StpUtil.getTokenValue();
		if (StrUtil.isNotBlank(token)) {
			template.header(SaTokenConst.AUTHORIZATION); // Clears out the header, no "clear" method available.
			template.header(SaTokenConst.AUTHORIZATION, String.format("%s %s", SaTokenConst.BEARER, token));
		}
	}
}
